package com.randb.easyhttp.body;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.Serializable;
import java.lang.ref.WeakReference;

/**
 * User: RandBII
 * Date: 2020/5/29
 * Description:
 */
public abstract class UIProgressResponseCallback implements ProgressResponseCallback {

    public static final int RESPONSE_UPDATE = 0X02;
    private final Handler mHandler = new UIHandler(Looper.getMainLooper(), this);

    @SuppressWarnings("unchecked")
    private static class UIHandler extends Handler {

        private WeakReference<UIProgressResponseCallback> reference;

        public UIHandler(Looper looper, UIProgressResponseCallback callback) {
            super(looper);
            reference = new WeakReference(callback);
        }


        @Override
        public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case RESPONSE_UPDATE:
                    UIProgressResponseCallback uiProgressResponseCallback = reference.get();
                    if (uiProgressResponseCallback != null) {
                        ProgressModel model = (ProgressModel) msg.obj;
                        uiProgressResponseCallback.onUIResponseProgress(model.currentBytes, model.contentLength, model.done);
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }

        }
    }

    public abstract void onUIResponseProgress(long currentBytes, long contentLength, boolean done);

    @Override
    public void onResponseProgress(long byteWrites, long contentLength, boolean done) {
        Message message = Message.obtain();
        message.obj = new ProgressModel(byteWrites, contentLength, done);
        message.what = RESPONSE_UPDATE;
        mHandler.sendMessage(message);

    }


    public static class ProgressModel implements Serializable {

        private long currentBytes;
        private long contentLength;
        private boolean done;

        public ProgressModel(long currentBytes, long contentLength, boolean done) {
            this.contentLength = currentBytes;
            this.contentLength = contentLength;
            this.done = done;
        }


        public long getCurrentBytes() {
            return currentBytes;
        }

        public void setCurrentBytes(long currentBytes) {
            this.currentBytes = currentBytes;
        }

        public long getContentLength() {
            return contentLength;
        }

        public void setContentLength(long contentLength) {
            this.contentLength = contentLength;
        }

        public boolean isDone() {
            return done;
        }

        public void setDone(boolean done) {
            this.done = done;
        }
    }
}
